<template>
  <div class="login-container">
    <h1>登陆组件</h1>
    <!-- 头部 -->
    <div class="login-box">
      <div class="login-img">
        <img src="../assets/logo.png" alt="">
      </div>
      <!-- 表单 -->
      <!-- 用户名 -->
      <el-form :model="loginForm" :rules="loginFormRul" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-form-item>

        <el-row>
          <el-col :offset="15">
            <el-button type="primary" @click="login">提交</el-button>
            <el-button @click="resetLogin">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

  </div>
</template>

<script>
export default {
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginFormRul: {
        username: [{ required: true, message: '请输入登录名称', trigger: 'blur' }],
        password: [{ required: true, message: '请输入登录名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    resetLogin () {
      this.$refs.loginFormRef.resetFields()
    },
    login () {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.post('login', this.loginForm)
        console.log(res)
        if (res.meta.status !== 200) {
          // 登陆失败，移除之前的token
          window.sessionStorage.removeItem('token')
          return this.$message.error('登陆失败')
        }
        this.$message.success('登陆成功')
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  background: #2b4d62;
  height: 100%;
  overflow: hidden;
}

.login-box {
  height: 304px;
  width: 450px;
  background: #fff;
  border-radius: 5px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.login-img {
  width: 130px;
  height: 130px;
  border: 1px solid #eee;
  border-radius: 50%;
  padding: 8px;
  box-shadow: 0 0 10px #eee;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background: #eee;
  }
}

.el-form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}
</style>
